/*
 * Copyright 2023 lzhpo
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.bitrate.dify.sse;

import com.bitrate.dify.response.ChatCompletionResponse;
import com.google.gson.Gson;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


@Slf4j
public class AbstractEventSourceListener extends EventSourceListener {

    private WxMpService wxMpService;

    private RedisTemplate<String, Object> redisTemplate;


    private String toUser = "";

    private String content = "";

    private String conversationId = "";

    public AbstractEventSourceListener(RedisTemplate<String, Object> redisTemplate, WxMpService wxMpService) {
        this.redisTemplate = redisTemplate;
        this.wxMpService = wxMpService;
    }

    @Override
    public void onClosed(EventSource eventSource) {
        log.info("Execute onClosed method.");
        try {
            //组装SSE并发送客服消息
            WxMpKefuMessage message = new WxMpKefuMessage();
            message.setToUser(toUser);
            message.setKfAccount("Ai3_Wisty317");
            message.setContent(content);
            message.setMsgType(WxConsts.KefuMsgType.TEXT);
            log.info("Send message to user: {}, content: {}", toUser, content);
            wxMpService.getKefuService().sendKefuMessage(message);
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        content = "";
    }

    @Override
    public void onEvent(EventSource eventSource, String id, String type, String data) {
        log.info("id: {}, type: {}, data: {}", id, type, data);
        ChatCompletionResponse response = new Gson().fromJson(data, ChatCompletionResponse.class);
        log.info("response: {}", response);
        //获取会话id
        String conversationId = response.getConversation_id();
        //获取要发送的人
        toUser = redisTemplate.opsForValue().get(conversationId).toString();
        log.info("conversationId: {}, toUser: {}", conversationId, toUser);
        //组装
        if (response.getEvent().equals("message")) {
            content += response.getAnswer();
        }
        log.info("content: {}", content);

    }

    @Override
    public void onFailure(EventSource eventSource, Throwable e, Response response) {
        super.onFailure(eventSource, e, response);
    }

    @Override
    public void onOpen(EventSource eventSource, Response response) {
        log.info("Execute onOpen method, response: {}", response);
    }
}
